package com.yunc.modules.api.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.text.StrSpliter;
import cn.hutool.crypto.digest.DigestUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yunc.common.utils.BaseConstant;
import com.yunc.common.utils.R;
import com.yunc.modules.api.annotation.AuthIgnore;
import com.yunc.modules.api.annotation.LoginUser;
import com.yunc.modules.shop.entity.*;
import com.yunc.modules.shop.entity.dto.CartDTO;
import com.yunc.modules.shop.entity.dto.ItemParamDTO;
import com.yunc.modules.shop.entity.dto.OrderDTO;
import com.yunc.modules.shop.entity.vo.OrderItemVO;
import com.yunc.modules.shop.entity.vo.OrderVO;
import com.yunc.modules.shop.service.*;
import com.yunc.modules.sys.entity.SysUser;
import com.yunc.modules.sys.service.ISysUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 接口
 *
 * @author tao cong cong
 * @create 2018/2/17 下午10:35
 */
@RestController
@RequestMapping("api")
public class ApiController {

    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private IMemberService memberService;
    @Autowired
    private IBannerService bannerService;
    @Autowired
    private IItemCatService itemCatService;
    @Autowired
    private IItemService itemService;
    @Autowired
    private IItemSpecsService itemSpecsService;
    @Autowired
    private IAddressService addressService;
    @Autowired
    private IOrderService orderService;
    @Autowired
    private IOrderItemService orderItemService;
    @Autowired
    private ICartService cartService;

    @AuthIgnore
    @GetMapping("userList")
    public R userList(){
        List<SysUser> sysUserList = sysUserService.list(null);
        return R.ok().put("sysUserList", sysUserList);
    }

    @GetMapping("userInfo")
    public R userInfo(@LoginUser SysUser sysUser){
        return R.ok("获取user成功").put("sysUser", sysUser);
    }

    @AuthIgnore
    @GetMapping("notToken")
    public R notToken(){
        return R.ok("无需token也能访问");
    }

    /**
     * 商城用户信息
     */
    @AuthIgnore
    @GetMapping("/member/info/{memberId}")
    public R memberInfo(@PathVariable String memberId){
        Member member = memberService.getById(memberId);
        return R.ok().put("member", member);
    }

    @AuthIgnore
    @PostMapping("/member/login")
    public R memberLogin(String phone, String password){
        // 使用md5加密
        Member member = memberService.getOne(new QueryWrapper<Member>().eq("phone", phone));
        if (member == null) {
            return R.error("无法查询到用户");
        }
        String passwordMd5 = DigestUtil.md5Hex(password);
        if (!StringUtils.equals(member.getPassword(), passwordMd5)) {
            return R.error("密码错误");
        }
        return R.ok().put("member", member);
    }

    /**
     * banner图
     */
    @AuthIgnore
    @GetMapping("/banner/list")
    public R bannerList(){
        QueryWrapper<Banner> ew = new QueryWrapper<>();
        List<Banner> list = bannerService.list(ew);
        return R.ok().put("list", list);
    }

    /**
     * 商品分类
     */
    @AuthIgnore
    @GetMapping("/itemCat/list")
    public R itemCatList(){
        QueryWrapper<ItemCat> ew = new QueryWrapper<>();
        List<ItemCat> list = itemCatService.list(ew);
        return R.ok().put("list", list);
    }

    /**
     * 商品热度
     */
    @AuthIgnore
    @GetMapping("/item/hotList")
    public R itemHotList(){
        QueryWrapper<Item> ew = new QueryWrapper<>();
        List<Item> list = itemService.list(ew);
        return R.ok().put("list", list);
    }

    /**
     * 所有商品
     */
    @AuthIgnore
    @GetMapping("/item/page")
    public R page(Page<Item> page, Item item){
        itemService.page(page, new QueryWrapper<>(item));
        return R.ok().put("data", page.getRecords()).put("hasNext", page.hasNext());
    }

    /**
     * 商品信息
     */
    @AuthIgnore
    @GetMapping("/item/info/{id}")
    public R itemInfo(@PathVariable String id){
        Item item = itemService.getById(id);
        // 取出params数据
        String paramData = item.getParamData();
        List<ItemParamDTO> itemParamList = new ArrayList<>();
        if (StringUtils.isNotEmpty(paramData)) {
            itemParamList = JSON.parseArray(paramData, ItemParamDTO.class);
        }
        // 查询itemSpecs
        QueryWrapper<ItemSpecs> ew = new QueryWrapper<>();
        ew.eq("item_id", id);
        List<ItemSpecs> itemSpecsList = itemSpecsService.list(ew);
        if (itemSpecsList != null && itemSpecsList.size() > 0) {
            Iterator<ItemSpecs> iterator = itemSpecsList.iterator();
            while (iterator.hasNext()) {
                ItemSpecs itemSpecs = iterator.next();
                if (itemSpecs.getStock() <= 0) {
                    iterator.remove();
                }
            }
        }
        return R.ok().put("item", item).put("itemParamList", itemParamList).put("itemSpecsList", itemSpecsList);
    }

    /**
     * 商品订单详情
     */
    @AuthIgnore
    @GetMapping("/orderItem/info/{orderItemJson}")
    public R itemOrderInfo(@PathVariable String orderItemJson){
        List<OrderItemVO> orderItemList = JSON.parseArray(orderItemJson, OrderItemVO.class);
        if (orderItemList != null && orderItemList.size() > 0) {
            for (OrderItemVO orderItem : orderItemList) {
                // 获取item的信息
                Item item = itemService.getById(orderItem.getItemId());
                orderItem.setBrandTitle(item.getBrandTitle());
                orderItem.setTitle(item.getTitle());
                orderItem.setImage(item.getImage());
                orderItem.setPrePrice(item.getPrePrice());
                orderItem.setOrigPrice(item.getOrigPrice());
                // 需要paramData
                // ItemSpecs itemSpecs = itemSpecsService.getById(orderItem.getSpecsSeq());
            }
        }
        return R.ok().put("orderItemList", orderItemList);
    }

    /**
     * 购物车
     */
    @AuthIgnore
    @GetMapping("/cart/getNum/{memberId}")
    public R getCartNum(@PathVariable String memberId){
        QueryWrapper<Cart> ew = new QueryWrapper<>();
        ew.eq("member_id", memberId);
        int count = cartService.count(ew);
        return R.ok().put("count", count);
    }

    /**
     * 购物车分页
     */
    @AuthIgnore
    @GetMapping("/cart/page")
    public R cartPage(Page<Cart> page, Cart cart){
        // Thread th = Thread.currentThread();
        // System.out.print(th.getId() + "..............................\t");
        List<CartDTO> cartList = cartService.pageInfo(page, cart);
        return R.ok().put("data", cartList).put("hasNext", page.hasNext());
    }

    /**
     * 加入购物车
     */
    @AuthIgnore
    @PostMapping("/cart/add")
    public R addCart(Cart cart){
        // 需要判断是否已加入过购物车,如果有则增加数量
        QueryWrapper<Cart> ew = new QueryWrapper<>();
        ew.eq("member_id", cart.getMemberId());
        ew.eq("item_id", cart.getItemId());
        if (cart.getSpecsId() != null) {
            ew.eq("specs_id", cart.getSpecsId());
        }
        Cart cartOne = cartService.getOne(ew);
        boolean flag;
        if (cartOne != null) {
            cartOne.setBuyNum(cartOne.getBuyNum() + cart.getBuyNum());
            flag = cartService.updateById(cartOne);
        } else {
            cart.setCreateTime(DateUtil.date());
            flag = cartService.save(cart);
        }
        if (!flag) {
            return R.error();
        }
        // 查询所有num
        QueryWrapper<Cart> ewC = new QueryWrapper<>();
        ew.eq("member_id", cart.getMemberId());
        int count = cartService.count(ewC);
        return R.ok().put("count", count);
    }

    /**
     * 根据主键删除地址
     */
    @AuthIgnore
    @DeleteMapping("/cart/delete/{ids}")
    public R addressDelete(@PathVariable String ids){
        if (StringUtils.isEmpty(ids)) {
            return R.error("传入值为空");
        }
        List<String> idsList = StrSpliter.split(ids, ',', 0, true, true);
        if (CollUtil.isEmpty(idsList)) {
            return R.error("传入值格式错误");
        }
        boolean flag = cartService.removeByIds(idsList);
        if (!flag) {
            return R.error();
        }
        return R.ok();
    }

    /**
     * 默认地址
     */
    @AuthIgnore
    @GetMapping("/address/default")
    public R defaultAddress(@RequestParam(required = false) String memberId,
                            @RequestParam(required = false)String addressId){
        Address address;
        if (StringUtils.isNotEmpty(addressId)) {
            address = addressService.getById(addressId);
        } else {
            address = addressService.getDefault(memberId);
        }
        if (address == null) {
            return R.error();
        }
        return R.ok().put("address", address);
    }

    /**
     * 查询相关人员的地址列表
     */
    @AuthIgnore
    @GetMapping("/address/list/{memberId}")
    public R addressList(@PathVariable Long memberId){
        QueryWrapper<Address> ew = new QueryWrapper<>();
        ew.eq("member_id", memberId);
        List<Address> list = addressService.list(ew);
        return R.ok().put("list", list);
    }

    /**
     * 保存地址
     */
    @AuthIgnore
    @PostMapping("/address/save")
    public R addressSave(Address address) {
        address.setCreateTime(DateUtil.date());
        boolean flag = addressService.saveAddress(address);
        if (!flag) {
            return R.error();
        }
        return R.ok();
    }

    /**
     * 地址更新
     */
    @AuthIgnore
    @PostMapping("/address/update")
    public R addressUpdate(Address address) {
        boolean flag = addressService.updateAddress(address);
        if (!flag) {
            return R.error();
        }
        return R.ok();
    }

    /**
     * 根据主键删除地址
     */
    @AuthIgnore
    @DeleteMapping("/address/delete/{id}")
    public R addressDelete(@PathVariable Long id){
        boolean flag = addressService.removeById(id);
        if (flag) {
            return R.ok();
        }
        return R.error();
    }

    /**
     * 提交订单
     */
    @AuthIgnore
    @PostMapping("/order/pay")
    public R orderPay(OrderVO orderInfo) {
        return orderService.orderPay(orderInfo);
    }

    @AuthIgnore
    @PostMapping("/order/payR")
    public R orderPayR(OrderVO orderInfo) {
        return orderService.orderPayR(orderInfo);
    }

    /**
     * 订单分页查询
     */
    @AuthIgnore
    @GetMapping("/order/page")
    public R orderPage(Page<OrderDTO> page, Order order){
        orderService.pageInfo(page, order);
        List<OrderDTO> records = page.getRecords();
        // 查询订单商品
        if (records != null && records.size() > 0) {
            for (OrderDTO orderDTO : records) {
                QueryWrapper<OrderItem> ew = new QueryWrapper<>();
                ew.eq("order_id", orderDTO.getId());
                List<OrderItem> orderItemList = orderItemService.list(ew);
                orderDTO.setOrderItemList(orderItemList);
            }
        }
        return R.ok().put("data", records).put("hasNext", page.hasNext());
    }

    @AuthIgnore
    @GetMapping("/order/num/{memberId}")
    public R orderNum(@PathVariable String memberId){
        // 待支付
        QueryWrapper<Order> ew = new QueryWrapper<>();
        ew.eq("member_id", memberId);
        ew.eq("status", BaseConstant.OrderStatus.NONPAY.getValue());
        int nonpay = orderService.count(ew);
        // 待发货
        QueryWrapper<Order> ewt = new QueryWrapper<>();
        ewt.eq("member_id", memberId);
        ewt.eq("status", BaseConstant.OrderStatus.PAY.getValue());
        int pay = orderService.count(ewt);
        // 待收货
        QueryWrapper<Order> ewth = new QueryWrapper<>();
        ewth.eq("member_id", memberId);
        ewth.eq("status", BaseConstant.OrderStatus.NONSEND.getValue());
        int nonsend = orderService.count(ewth);
        return R.ok().put("nonpay", nonpay).put("pay", pay).put("nonsend", nonsend);
    }
}
